package com.yixq.springboot.dao.impl;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.yixq.springboot.bean.SpringBootUser;
import com.yixq.springboot.dao.SpringBootUserDao;
import com.yixq.springboot.util.base.JdbcDaoImpl;
import com.yixq.springboot.util.base.Page;
import com.yixq.springboot.util.base.Sql;

@Repository
public class SpringBootUserDaoImpl extends JdbcDaoImpl implements SpringBootUserDao {

	//@Autowired
	//private JdbcTemplate jdbcTemplate;

	@Override
	public int insert(SpringBootUser springbootUser) {
		String sql = "insert into springboot_user (name, create_time) values (?, ?)";
		return jdbcTemplate.update(sql, springbootUser.getName(), springbootUser.getCreateTime());
	}

	@Override
	public int deleteById(int id) {
		String sql = "delete from springboot_user where id=?";
		return jdbcTemplate.update(sql, id);
	}

	@Override
	public int updateById(SpringBootUser springbootUser) {
		String sql = "update springboot_user set name=?, create_time=? where id=?";
		return jdbcTemplate.update(sql, springbootUser.getName(), springbootUser.getCreateTime(), springbootUser.getId());
	}

	@Override
	public SpringBootUser selectById(int id) {
		String sql = "select * from springboot_user where id=?";
		/*return jdbcTemplate.queryForObject(sql, new RowMapper<springbootUser>() {
			@Override
			public springbootUser mapRow(ResultSet rs, int rowNum) throws SQLException {
				springbootUser springbootUser = new springbootUser();
				springbootUser.setId(rs.getInt("id"));
				springbootUser.setName(rs.getString("name"));
				springbootUser.setCreateTime(rs.getDate("create_time"));
				return springbootUser;
			}
		}, id);*/
		
		return queryForObject(sql, SpringBootUser.class, id);
	}

	@Override
	public Page<SpringBootUser> queryForPage(int pageCurrent, int pageSize, String name){
		// 确定参数
		/*String sql = "select * from springboot_user where name=?";
		return queryForPage(sql.toString(), pageCurrent, pageSize, springbootUser.class, name);*/
		
		// 若name可能为空，则要进行判定，如下
		/*StringBuffer sql = new StringBuffer("select * from springboot_user where 1");
		if(!StringUtils.isNullOrEmpty(name)){
			// Sql.checkSql 的作用是防止sql注入
			sql.append(" and name = '").append(Sql.checkSql(name)).append("' ");
		}
		return queryForPage(sql.toString(), pageCurrent, pageSize, springbootUser.class);*/
		
		// 若要like查询，如下
		StringBuffer sql = new StringBuffer("select * from springboot_user where 1");
		if(!StringUtils.isEmpty(name)){
			// Sql.checkSql 的作用是防止sql注入
			sql.append(" and name like '%").append(Sql.checkSql(name)).append("%' ");
		}
		return queryForPage(sql.toString(), pageCurrent, pageSize, SpringBootUser.class);
	}	





}
